#!/usr/bin/env bash

# ===========================================================================
# File: "othereditor"
#                        Created: 2019-02-07 14:59:08
#              Last modification: 2019-02-10 18:41:35
# Author: Bernard Desgraupes
# e-mail: <bdesgraupes@users.sourceforge.net>
# Copyright (c) 2019 Alpha Community
# All rights reserved.
# This file is part of the AlphaCocoa project.
# Description:
# this script is meant for integration of Alpha with TexShop
# (https://pages.uoregon.edu/koch/texshop/) so that TexShop may use Alpha
# as external text editor and perform synchronization therewith.
# ===========================================================================

VERSION_NUMBER="0.1"

if [ -L $0 ] ; then
	AED_SELF_PATH=`readlink $0`
else
	AED_SELF_PATH=$0
fi

# Initialization
AED_DEBUG=0
AED_APP_PATH=
AED_OPTS=
AED_ALPHA_ID=net.sourceforge.alphacocoa

function status_debug {
    if [ $AED_DEBUG == 1 ]; then
        echo "$1" 1>&2
    fi
}

print_usage () {
	echo "Usage: "
    echo "    " $(basename $0) "[options] ?line? file" 
    echo "    " $(basename $0) "[-h|-v]" 
    echo "Options:"
    echo "    -d        print debugging information"
    echo "    -h        print usage"
    echo "    -v        print version"
#     echo "Linespec format: l1[.c1][,l2[.c2]])"
    echo "Examples:"
    echo "    $(basename $0) 12 foo.tex"
    echo "    $(basename $0) 123 foo.log"
}

# Return the path of the first running instance of Alpha.app
running_alpha () {
	echo `ps -x -o command | grep Alpha.app/Contents/MacOS/Alpha | grep -v grep \
			| head -n1 | sed -e 's/-psn.*//' -e 's:/Contents/MacOS/Alpha::'`
}


# Parse the command line options
while getopts ":dhv" opt; do
	case $opt in
		d )
			AED_DEBUG=1
			AED_OPTS="$AED_OPTS -d" ;;
		h )
			echo othereditor "- version $VERSION_NUMBER" 
			echo "Copyright (c) 2018-`date "+%Y"`, Bernard Desgraupes"
			echo "Edit a file at given line with Alpha."
			echo "This is part of the AlphaCocoa project:"
			echo "http://sourceforge.net/projects/alphacocoa"
			print_usage 
			exit 0 ;;
		v )
			echo $VERSION_NUMBER 
			exit 0 ;;
		\? )
			# pass on
			;;
	esac
done

# Skip the processed options
shift $((--OPTIND))


if [ $# == 0 -o $# -gt 2 ] ; then
	echo "Error: wrong number of arguments" 
	print_usage
	exit 1
elif [ $# == 2 ] ; then
	AED_LINESPEC=$1
	AED_FILENAME=$2
else
	AED_LINESPEC=1
	AED_FILENAME=$1	
fi

# Parse the line specification
if ! [[ "$AED_LINESPEC" =~ ([[:digit:]]+)(\.([[:digit:]]+))?([-,:]([[:digit:]]+)(\.([[:digit:]]+))?)? ]] 
then
	echo "wrong format for linespec. Should be of the form 'l1[.c1][,l2[.c2]]'."
	exit 1
fi

status_debug "debugging=$AED_DEBUG"

running=`running_alpha`
if [ "$running" != "" ] ; then
	status_debug "Alpha is already running"
	AED_APP_PATH=$running
else
	# Look if this script is inside a bundle
	if [ -e $AED_SELF_PATH/../../../Alpha.app ] ; then
		status_debug "script is in bundle"
		open $AED_SELF_PATH/../../../Alpha.app
	else 
		status_debug "launching $AED_ALPHA_ID"
		open -b $AED_ALPHA_ID
	fi
	AED_APP_PATH=`running_alpha`
fi

if [ "$AED_APP_PATH" == "" ] ; then
	echo "can't find Alpha"
	exit 1
fi
status_debug "App path: $AED_APP_PATH"

AED_ALPHAC=$AED_APP_PATH/Contents/Resources/alphac
if ! [ -e $AED_ALPHAC ]  ; then
	echo "can't find alphac script"
	exit 1
fi
status_debug "alphac path: $AED_ALPHAC"

# Invoke alphac
$AED_ALPHAC $AED_OPTS +$AED_LINESPEC -- $AED_FILENAME

